﻿Imports System.Data.SqlClient

Imports System.Text.RegularExpressions

Public Class FormCustomerEditor

    
    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click

        If Me.txtCustomerName.Text.Trim() = "" Then
            MsgBox("Please input customer name!")
            txtCustomerName.Focus()
            Exit Sub
        End If

        If Me.txtCustomerName.Text.Length < 2 Or Me.txtCustomerName.Text.Length > 500 Then
            MsgBox("Customer name must be between 2 to 500 charactors lenght!")
            txtCustomerName.SelectAll()
            txtCustomerName.Focus()
            Exit Sub
        End If


        Cmd.Parameters("@Name") = txtCustomerName.Text
        Cmd.Parameters("@Id") = txtCustomerId.Text
        Dim count As Int16 = Cmd.ExecuteScalar("SELECT COUNT(*) FROM Customer WHERE CustomerName = @Name AND CustomerId<>@Id")
        If count > 0 Then
            MsgBox("Customer name is already exists!")
            txtCustomerName.SelectAll()
            txtCustomerName.Focus()
            Exit Sub 
        End If

        If Me.txtPhone.Text.Trim() = "" Then
            MsgBox("Please input phone!")
            txtPhone.Focus()
            Exit Sub
        End If
 
        If Validator.IsPhone(Me.txtPhone.Text) = False Then
            MsgBox("Please input a correct phone format!")
            txtPhone.SelectAll()
            txtPhone.Focus()
            Exit Sub
        End If


        Cmd.Parameters("@CustomerName") = Me.txtCustomerName.Text
        Cmd.Parameters("@Phone") = Me.txtPhone.Text
        Cmd.Parameters("@Address") = Me.txtAddress.Text 
        If Me.txtCustomerId.Text = "" Then
            Cmd.ExecuteNonQuery("INSERT INTO Customer VALUES(@CustomerName,@Phone,@Address,1);")
        Else
            Cmd.Parameters("@CustomerId") = txtCustomerId.Text
            Cmd.ExecuteNonQuery("UPDATE Customer SET CustomerName=@CustomerName,Phone=@Phone,Address=@Address WHERE CustomerId=@CustomerId")
        End If

        Me.DialogResult = Windows.Forms.DialogResult.OK

    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click

        Me.DialogResult = Windows.Forms.DialogResult.Cancel

    End Sub
End Class